<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://"
          + request.getServerName() + ":" + request.getServerPort()
          + path + "/";
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <%--<meta http-equiv="Content-Type" content="text/html; charset=GB2312"/>--%>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <%--<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">--%>
  <%--<meta content="yes" name="apple-mobile-web-app-capable">--%>
  <%--<meta content="black" name="apple-mobile-web-app-status-bar-style">--%>
  <%--<meta content="telephone=no" name="format-detection">--%>
    <title>数据对比</title>
  <link rel="stylesheet" type="text/css" href="<%=basePath%>css/easyui.css" />
  <link rel="stylesheet" type="text/css" href="<%=basePath%>css/icon.css" />
  <script type="text/javascript" src="<%=basePath%>js/jquery.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/jquery-1.11.2.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/jquery.easyui.min.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/easyui-lang-zh_CN.js"></script>
  <script type="text/javascript" src="<%=basePath%>js/json2.js"></script>
  <link rel='stylesheet' href='<%=basePath%>js/jquery-datePicker.css' />
  <script type='text/javascript' src='<%=basePath%>js/jquery-datePicker.js'></script>
  <%--<link rel="stylesheet" href="<%=basePath%>js/jquery-datePicker.css" />--%>
  <%--<script type="text/javascript" src="<%=basePath%>js/jquery-datePicker.js"></script>--%>
</head>
<body>
<div id="main" class="easyui-layout" fit="true" style="width: 100%;">
  <div id="center" region="center" style="background:#eee; overflow:hidden;border:0px;width: 900px;">
    <table toolbar="#div_toolbar" id="compareGrid" fitColumns="true" fit="true"  style="width:auto;height:100%"></table>
  </div>
  <div id="div_toolbar" style="">
    <span style="">
      <label style="color: #313031">数据源库：</label>
      <select id="src_ds" class="easyui-combobox" editable="false" style="width: 90px" panelHeight="150px"></select>
      <label style="color: #313031">备份库：</label>
      <select id="tgt_ds" class="easyui-combobox" editable="false" style="width: 90px" panelHeight="150px"></select>
      <label style="color: #313031">数据源表：</label>
      <select id="src_tab" class="easyui-combobox" editable="false" style="width: 90px" panelHeight="150px"></select>
      <label style="color: #313031">备份表：</label>
      <select id="tgt_tab" class="easyui-combobox" editable="false" style="width: 90px" panelHeight="150px"></select>
      <label style="color: #313031">选择对比列：</label>
      <select id="column-box" class="easyui-combobox" multiple="true" style="width: 150px" panelHeight="300px"></select>
      <label style="color: #313031">选择对比方式：</label>
      <select id="compare-pattern" class="easyui-combobox" editable="false" style="width: 120px" panelHeight="150px">
        <option value="按主键开始位">按主键开始位</option>
        <option value="按时间段对比">按时间段对比</option>
        <option value="按条数对比">按条数对比</option>
      </select>
    </span>
    <span class="num-span" style="display: none">
      <label style="color: #313031" class="num-label">对比条数：</label>
      <select id="num-box" class="easyui-combobox" editable="false" style="width: 80px" panelHeight="150px">
        <option value="100">100</option>
        <option value="200">200</option>
        <option value="500">500</option>
        <option value="1000">1000</option>
      </select>
    </span>
    <span class="time-span" style="display: none">
      <label class="time-label" style="">时间列：</label>
      <select id="time-box" class="easyui-combobox" editable="false" style="width: 150px;" panelHeight="150px"></select>
      <label class="datetime" style="">选择时间:</label>
      <input type="text" id="datetime" readonly="readonly" value="" style="width: 280px;" placeholder="点击选择时间"/>
    </span>
    <span class="primary-span" style="display: none">
      <label class="primary-label" style="">主键开始位：</label>
      <input id="primary-key" class="easyui-numberbox" style="width: 80px;" min="0"/>
    </span>
    <span style="display: none">
      <select id="sort-box" class="easyui-combobox" editable="false" style="width: 80px;display: none;" panelHeight="150px">
        <option value="desc">降序</option>
        <option value="asc">升序</option>
      </select>
    </span>
    <%--<label>时间字段:</label>--%>
    <%--<input type="checkbox" id="isTime"/>--%>
    <script type="text/javascript">
      $("#datetime").datePicker({
        format:"YYYY-MM-DD HH:mm:ss",            //格式化
        separator:" ~ ",                         //分隔标示
        singleDate:false,                         //单选日期        默认false就是双选日期了
//        minDate:new Date(),                      //最小日期
        maxDate:new Date("2100-12-12"),          //最大日期
        setValue:function(s1,s2){                //自定义输出
          $("#datetime").val(s1 + ' ~ ' + s2)
        }
      });
      function dateFormat(date){
        var y = date.getFullYear();
        var m = date.getMonth()+1;
        var d = date.getDate();
        var h = date.getHours();
        var min = date.getMinutes();
        var sec = date.getSeconds();
        var str = y+'/'+(m<10?('0'+m):m)+'/'+(d<10?('0'+d):d)+'/'+' '+(h<10?('0'+h):h)+':'+(min<10?('0'+min):min)+':'+(sec<10?('0'+sec):sec);
        return str;
      }
      function parserFormat(s){
        if (!s) return new Date();
        var y = s.substring(0,4);
        var m =s.substring(5,7);
        var d = s.substring(8,10);
        var h = s.substring(11,14);
        var min = s.substring(15,17);
        var sec = s.substring(18,20);
        if (!isNaN(y) && !isNaN(m) && !isNaN(d) && !isNaN(h) && !isNaN(min) && !isNaN(sec)){
          return new Date(y,m-1,d,h,min,sec);
        } else {
          return new Date();
        }
      }
    </script>
    </select>
    <!-- 对比按钮-->
    <a id="compare" class="easyui-linkbutton" title="对比" iconCls="icon-reload" plain="true">对比</a>
    <!-- 及时按钮-->
    <a id="immediately" class="easyui-linkbutton" title="执行即时任务" disabled="true" iconCls="icon-reload" plain="true">执行即时任务</a>
  </div>
</div>
</body>
<script type="text/javascript">
  var offset = 1;
  var limit = 20;
  var dataGrid,editRow,rowIndex,tgtID,srcTab,srcID,indexCompare,uuid,total;

  $(function () {
    $('.primary-span').show();
    $('.primary-span').addClass('active');

    /**初始化加载源数据源下拉列表**/
    $.ajax({
      url:'<%=basePath%>compare/getDataSourceCombobox?newDate='+new Date(),
      type : 'post',
      dataType : 'json',
      timeout:20000,
      success : function(res) {
        if(res != null && res.data.length > 0){
          $('#src_ds').combobox("loadData", res.data);
        }
      },
      error: function (error) {
        $.messager.alert("系统繁忙，请稍后再试！");
      }
    });

    $("#isTime").on("change", function (){
      if($(this).is(":checked")){
        $("#time-box").combobox({disabled:false});
        $("#datetime").show();
        $(".datetime").show();
      } else {
        $("#time-box").combobox({disabled:true});
        $("#datetime").hide();
        $(".datetime").hide();
      }
    });

    $("#compare-pattern").combobox({
      onSelect:function(record){
        if(record.value == '按条数对比') {
          $('.num-span').show();
          $('.num-span').addClass('active');
          $('.time-span').hide();
          $('.time-span').removeClass('active');
          $('.primary-span').hide();
          $('.primary-span').removeClass('active');
          $("#immediately").linkbutton({disabled:true});
          $("#datetime").val('');
          $('#primary-key').numberbox('setValue',0);
        } else if(record.value == '按时间段对比') {
          $('.time-span').show();
          $('.time-span').addClass('active');
          $('.num-span').hide();
          $('.num-span').removeClass('active');
          $('.primary-span').hide();
          $('.primary-span').removeClass('active');
          $("#immediately").linkbutton({disabled:false});
          $('#primary-key').numberbox('setValue',0);
        } else if(record.value == '按主键开始位'){
          $('.primary-span').show();
          $('.primary-span').addClass('active');
          $('.num-span').hide();
          $('.num-span').removeClass('active');
          $('.time-span').hide();
          $('.time-span').removeClass('active');
          $("#immediately").linkbutton({disabled:false});
          $("#datetime").val('');
        }
      }
    });

    $("#src_ds").combobox({
      onSelect:function(record){
        var id = record.value;
        var text = record.text;
        $("#tgt_ds").combobox("clear");
        $("#tgt_tab").combobox("clear");
        $("#src_tab").combobox("clear");
        tgtID= undefined,srcTab=undefined;
        srcID = id;
        if(tgtID != undefined && srcTab != undefined) {
          var param = {srcDsId:parseInt(srcID),srcDsTable:srcTab,tgtDsId:parseInt(tgtID)};
          loadTgtTabData(param);
        } else {
          $.ajax({
            url:'<%=basePath%>compare/getTgtDataSourceCombobox/'+id,
            type:'POST',
            data:{id:id},
            timeout:20000,
            success:function (res){
              if(res.tgtData != null && res.tgtData.length > 0) {
                $("#tgt_ds").combobox("loadData", res.tgtData);
              }
              if(res.tableData != null && res.tableData.length > 0) {
                $("#src_tab").combobox("loadData", res.tableData);
              }
            },
            error: function (error) {
              $.messager.alert("系统繁忙，请稍后再试！");
            }
          });
        }
    }
    });

    $("#tgt_ds").combobox({
      onSelect:function(record){
        var id = record.value;
        var text = record.text;
        $("#src_tab").combobox("clear");
        srcTab=undefined;
        tgtID = id;
        if(srcID != undefined && srcTab != undefined){
          var param = {srcDsId:parseInt(srcID),srcDsTable:srcTab,tgtDsId:parseInt(tgtID)};
          loadTgtTabData(param);
        }
      }
    });


    $("#src_tab").combobox({
      onSelect:function(record){
        srcTab = record.text;
        if(srcID != undefined && tgtID != undefined) {
          var param = {srcDsId:parseInt(srcID),srcDsTable:srcTab,tgtDsId:parseInt(tgtID)};
          loadTgtTabData(param);
        }
      }
    });





    $("#immediately").bind("click",function(){
      var opt = $("#immediately").linkbutton('options');
      if(!opt.disabled) {
        $("#immediately").linkbutton({disabled:true});
        var tgtTab = $("#tgt_tab").combobox("getText");
        var column = $("#column-box").combobox("getText");
        if(column == undefined || column == null || column == '') {
          column = "全部";
        }
        var sort = $("#sort-box").combobox("getValue");
        var limit = $("#num-box").combobox("getValue");
        var params;
        if($(".time-span").hasClass("active")) {
          var startTime,endTime;
          var datetime = $("#datetime").val();
          var columnTime = $("#time-box").combobox("getValue");
          if(datetime != null && datetime != '' && columnTime != undefined && columnTime != null && columnTime != ''){
            var dates = datetime.split(' ~ ');
            if(dates.length > 1) {
              startTime = dates[0];
              endTime = dates[1];
              params = {
                column:column,sort:sort,isTime: true,limit:limit,srcTab:srcTab,srcDsId:srcID,
                tgtTab:tgtTab,tgtDsId:tgtID,startTime:startTime,endTime:endTime,columnTime:columnTime,primaryKey:-1
              };
              immediatelyData(params);
            } else {
              $.messager.alert("提示","请选择时间列及对比时间！");
              $("#immediately").linkbutton({disabled:false});
            }
          } else {
            $.messager.alert("提示","请选择时间列及对比时间！");
            $("#immediately").linkbutton({disabled:false});
          }
        } else  if($('.primary-span').hasClass('active')){
          var primaryKey = $('#primary-key').numberbox('getValue');
          if(primaryKey > 0){
            params = {
              column:column,sort:sort,limit:limit,isTime: false,srcTab:srcTab,srcDsId:srcID,tgtTab:tgtTab,
              tgtDsId:tgtID,startTime:'',endTime:'',columnTime:'',primaryKey:primaryKey
            };
            immediatelyData(params);
          } else {
            $.messager.alert("提示","请输入有效的主键值！");
            $("#immediately").linkbutton({disabled:false});
          }
        }
      }
    });

    $("#compare").bind("click", function (){
      var opt = $("#compare").linkbutton('options');
      if(!opt.disabled) {
        $("#compare").linkbutton({disabled:true});
        var tgtTab = $("#tgt_tab").combobox("getText");
        var column = $("#column-box").combobox("getText");
        if(column == undefined || column == null || column == '') {
          column = "全部";
        }
        var sort = $("#sort-box").combobox("getValue");
        var limit = $("#num-box").combobox("getValue");
        var params;
        if($(".time-span").hasClass("active")) {
          var startTime,endTime;
          var datetime = $("#datetime").val();
          var columnTime = $("#time-box").combobox("getValue");
          if(datetime != null && datetime != '' && columnTime != undefined && columnTime != null && columnTime != ''){
            var dates = datetime.split(' ~ ');
            if(dates.length > 1) {
              startTime = dates[0];
              endTime = dates[1];
              params = {
                column:column,sort:sort,isTime: true,limit:limit,srcTab:srcTab,srcDsId:srcID,tgtTab:tgtTab,
                tgtDsId:tgtID,startTime:startTime,endTime:endTime,columnTime:columnTime,primaryKey:-1
              };
            compareData(params);
            } else {
              $.messager.alert("提示","请选择时间列及对比时间！");
              $("#compare").linkbutton({disabled:false});
            }
          } else {
            $.messager.alert("提示","请选择时间列及对比时间！");
            $("#compare").linkbutton({disabled:false});
          }
        } else if($('.num-span').hasClass('active')) {
          params = {
            column:column,sort:sort,limit:limit,isTime: false,srcTab:srcTab,srcDsId:srcID,
            tgtTab:tgtTab,tgtDsId:tgtID,startTime:'',endTime:'',columnTime:'',primaryKey:-1
          };
          compareData(params);
        } else  if($('.primary-span').hasClass('active')){
          var primaryKey = $('#primary-key').numberbox('getValue');
          if(primaryKey > 0){
            params = {
              column:column,sort:sort,limit:limit,isTime: false,srcTab:srcTab,
              srcDsId:srcID,tgtTab:tgtTab,tgtDsId:tgtID,startTime:'',endTime:'',columnTime:'',primaryKey:primaryKey
            };
            compareData(params);
          } else {
            $.messager.alert("提示","请输入有效的主键值！");
            $("#compare").linkbutton({disabled:false});
          }
        }
      }
    });

    dataGrid = $('#compareGrid').datagrid({//表格数据
      singleSelect: true,
      pagination : true,
      rownumbers:true,
      fitColumns :true
    });
  });

  /**组装动态列数据**/
  function buildingColumn(data){
    var columns = [];
    columns.push({field:'ck',checkbox:true});
    for(var i = 0;i < data.length;i++){
      if(data[i] == 'split_column'){
        var column = {"field":data[i],"title":" ","width":"3px","align":"center",styler:function(value,rowData,rowIndex){
          return "background:#000";
        }}
      } else {
        if(data[i].indexOf("tgt_") != -1){
          var column = {"field":data[i],"title":data[i],"align":"center","sortable":true,
            styler:function(value,rowData,rowIndex){

              var other_val = rowData[this.field.replace("tgt_","")];

              if(value != other_val ){
                return "background:#2ddada;";
              }

            }
          };
        } else {
          var column = {"field":data[i],"title":"src_" + data[i],"align":"center","resizable":true,"sortable":true,
            styler:function(value,rowData,rowIndex){

              var other_val = rowData['tgt_'+this.field];

              if(value != other_val ){
                return "background:#2ddada;";
              }

            }
          };
        }
      }
      columns.push(column);
    }
    return columns;
  }

  /**
   * 执行即时任务
   **/
  function immediatelyData(params){
    if(params.srcDsId != undefined && params.tgtDsId != undefined && params.srcTab != undefined && params.tgtTab != undefined) {
      $.ajax({
        url: '<%=basePath%>task/immediately',
        type: 'post',
        data: params,
        timeout: 20000,
        success: function (res) {
          $.messager.show({
            title:'提示',
            width:250,
            height:140,
            msg:res.message
          });
          $("#immediately").linkbutton({disabled:false});
        },
        error: function (error) {
          $.messager.show({
            title:'提示',
            width:250,
            height:140,
            msg:error
          });
          $("#immediately").linkbutton({disabled:false});
        }
      });
    }
  }

  /** 对比数据**/
  function compareData(params){
    if(params.srcDsId != undefined && params.tgtDsId != undefined && params.srcTab != undefined && params.tgtTab != undefined) {
      $.ajax({
      url:'<%=basePath%>compare/compare',
      type:'post',
      data:params,
      timeout:20000,
      success:function(res){
        $("#compare").linkbutton({disabled:false});
        if(res.code == 0){
          var srcColumns = [];
          if(res.data.columnList.length > 0) {
            srcColumns.push(buildingColumn(res.data.columnList));
            $("#compareGrid").datagrid({columns:srcColumns});
            $("#compareGrid").datagrid("loadData",res.data.resultList);
            uuid = res.data.uuid;
            total =res.data.total;
            //grid的分页信息
            $('#compareGrid').datagrid('getPager').pagination({//分页对象
              pageSize: 100,
              total: res.total,
              pageNumber: 1,
              showRefresh:false,
              pageList:[100],
              onSelectPage : function(pageNumber, pageSize) {
                var param ={page:pageNumber,limit:pageSize,uuid:uuid}
                loadPages(param);
              }
            });
            $("#compare").linkbutton({disabled:false});
          } else {
            $.messager.show({
              title:'提示',
              width:250,
              height:140,
              msg:"没有任何修改过的数据！"
            });
            $("#compare").linkbutton({disabled:false});
          }
        } else if (res.code == 50000){
          $.messager.show({
            title:'提示',
            width:250,
            height:140,
            msg:res.message
          });
          $("#compare").linkbutton({disabled:false});
        }
      },
        error: function (error) {
          console.log(error)
          $.messager.show({
            title:'提示',
            width:250,
            height:140,
            msg:error
          });
          $("#compare").linkbutton({disabled:false});
        }
      });
    } else {
      $.messager.show({
        title:'提示',
        width:250,
        height:140,
        msg:"请选择完整的数据源及表名！"
      });
      $("#compare").linkbutton({disabled:false});
    }
  }

  /**分页加载对比记录数据**/
  function loadPages(param){
    $.ajax({
      url:'<%=basePath%>compare/loadPages',
      type:'post',
      data:param,
      timeout:20000,
      success:function (res){
        console.log(res)
        $('#compareGrid').datagrid({
          data:res.data
        });
        $('#compareGrid').datagrid("loaded");
        $('#compareGrid').datagrid('getPager').pagination({//分页对象
          pageSize: 100,
          total: total,
          pageNumber: param.page,
          pageList:[100],
          onSelectPage : function(pageNumber, pageSize) {
            var param ={page:pageNumber,limit:pageSize,uuid:uuid};
            loadPages(param);
          }
        });
      },
      error: function (error) {
        $.messager.alert("请求失败，请刷新再试！！");
      }
    });
  }
  /**
    *加载模板数据源表名
    * @param param
   */
  function loadTgtTabData(param){
    $("#tgt_tab").combobox("clear");
    $("#column-box").combobox("clear");
    $("#time-box").combobox("clear");
    $("#tgt_tab").combobox("loadData", []);
    $("#column-box").combobox("loadData", []);
    $("#time-box").combobox("loadData", []);
    $.ajax({
      url:'<%=basePath%>compare/getTgtSourceTable',
      type:'post',
      data:param,
      success:function(res){
        console.log(res)
        if(res.data != null && res.data.data.length > 0){
          $("#tgt_tab").combobox("loadData", res.data.data);
          $("#column-box").combobox("loadData", res.data.columnData);
          $("#time-box").combobox("loadData", res.data.tableStrutListMap);
        } else {
          $.messager.show({
            title:'提示',
            width:250,
            height:140,
            msg:"目标数据表没有任何数据！！"
          });
        }
      },
      error: function (error) {
        $.messager.show({
          title:'提示',
          width:250,
          height:140,
          msg:"请求失败，请刷新再试！！"
        });
      }
    });
  }
</script>
</html>
